Azure OpenAI 是由 Microsoft 提供的雲端服務,允許企業在 Azure 平台上使用 OpenAI 的模型。主要是預防企業串接後資料被用來訓練,以下介紹其主要特點:
流量管制:
資料安全:
企業整合:
Gateway API 通常指的是直接從 OpenAI 提供的 API 入口進行串接,而非透過 Azure 等第三方平台。公司內部可自行管制訪問流量,設定好後即可確保是內網才可進行訪問,以下介紹其主要特點:
流量管制:
資料安全:
整合與控制:
| 特點 | Azure OpenAI | Gateway API | 
|---|---|---|
| 流量管制 | 提供嚴格的流量管理和限制功能,支持自定義配額和速率限制 | 基本的流量控制,需要用戶自行管理 API 請求速率和流量 | 
| 資料安全 | 提供高度安全的基礎設施和數據加密,數據不會用於模型訓練 | 保證數據不會用於模型訓練,但安全功能較 Azure 不全面 | 
| 企業整合 | 可與 Azure 的身份驗證、監控、分析等服務無縫整合 | 提供更直接的 API 控制,但缺乏 Azure 的企業級工具和支持 | 
| 部署選項 | 支持混合雲和多雲環境,靈活的企業級部署方案 | 提供靈活的 API 接入,適合自我管理和控制的用戶 | 
| 隱私與合規 | 符合多項隱私和合規性認證(如 GDPR),提供完善的合規工具 | 支持基本的隱私法規合規(如 GDPR),但缺乏全面合規工具 | 
import os
from openai import AzureOpenAI
client = AzureOpenAI(
  azure_endpoint = "", 
  api_key="",  
  api_version=""
)
response = client.chat.completions.create(
    model="gpt-4o", # model = "deployment_name".
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},
        {"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},
        {"role": "user", "content": "Do other Azure AI services support this too?"}
    ]
)
print(response.choices[0].message.content)
要使用 Gateway 串接 OpenAI 模型,需要先建立並配置 Gateway。以下是詳細的步驟:
選擇主機環境:
設置 API Gateway:
設置 API 路由:
gpt-4o 或其他模型的請求轉發到對應的 OpenAI API 端點。/gateway/chat/completions/gpt-4o 轉發到 GPT-4 OpenAI API。/gateway/chat/completions/gpt-35-turbo 轉發到 GPT-3.5 OpenAI API。配置認證:
將 Gateway 部署到雲端或本地環境:
測試 Gateway:
獲取 Gateway 的 URL:
https://your-gateway-name.azurewebsites.net/gateway/chat/completions/gpt-4o。發送請求:
requests 模組、Postman、或 cURL)來發送請求。import requests
url = "https://your-gateway-name.azurewebsites.net/gateway/chat/completions/gpt-4o"
headers = {
    "api-key": "your-gateway-api-key",
    "Content-Type": "application/json"
}
payload = {
    "messages": [
        {"role": "system", "content": "你是一個聰明的程式設計師"},
        {"role": "user", "content": "python算是OOP嗎?"}
    ]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
管理和監控 Gateway:
這樣,你的 Gateway 就能夠充當一個中間層,方便用戶訪問和管理 OpenAI 的服務囉!
最後,若有想要測試AOAI、Gateway response time的朋友,這邊也提供範例程式碼
import os
import requests
from dotenv import load_dotenv
from datetime import datetime
import csv
import json
# 加載 .env 文件中的環境變數
load_dotenv()
# 獲取 API 基本信息
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
api_key = os.getenv("AZURE_OPENAI_API_KEY")
api_version = "2024-02-01"
def send_openai_request(model, messages):
    try:
        # 記錄開始時間
        start_time = datetime.now()
        print(f"Start time: {start_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
        # 設置請求 URL 和 headers
        url = f"{azure_endpoint}/openai/deployments/{model}/chat/completions?api-version={api_version}"
        headers = {
            "Content-Type": "application/json",
            "api-key": api_key
        }
        # 創建 chat completion 請求
        data = {
            "messages": messages
        }
        response = requests.post(url, headers=headers, data=json.dumps(data), verify=False)
        # 記錄結束時間
        end_time = datetime.now()
        print(f"End time: {end_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
        # 計算總共花費的時間
        duration = end_time - start_time
        print(f"Time taken: {duration}")
        # 檢查請求是否成功
        if response.status_code == 200:
            return start_time, end_time, duration, response.json()
        else:
            print(f"Request failed with status code {response.status_code}: {response.text}")
            return None, None, None, None
    except Exception as e:
        print(f"Error: {e}")
        return None, None, None, None
# 嵌入模型名稱列表
models = [
    "gpt-35-turbo-0613",
    "gpt-4-turbo",
    "gpt-4o"
]
# 準備發送到 OpenAI 的數據
input_text = "電動車的普及及如何影響保險行業的風險評估和定價策略?請簡要說明。"
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": input_text}
]
# 開啟 CSV 文件,準備寫入
with open('chat_completion_results.csv', 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['model', 'start_time', 'end_time', 'duration']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for model in models:
        for i in range(50):
            print(f"第 {i+1} 次 - 模型: {model}")
            start_time, end_time, duration, response = send_openai_request(model, messages)
            if start_time and end_time and duration:
                writer.writerow({
                    'model': model,
                    'start_time': start_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'end_time': end_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'duration': duration
                })
                print(response['choices'][0]['message']['content'])
            else:
                print("Request failed, skipping this iteration.")
            print('\n')
import requests
from rich import print as pprint
import json
from datetime import datetime
import csv
def send_openai_request(url, headers, payload):
   # 記錄開始時間
   start_time = datetime.now()
   print(f"Start time: {start_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
   # 發送 POST 請求
   response = requests.post(url, headers=headers, json=payload, verify=False)
   # 記錄結束時間
   end_time = datetime.now()
   print(f"End time: {end_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
   # 計算總共花費的時間
   duration = end_time - start_time
   print(f"Time taken: {duration}")
   return start_time, end_time, duration
# 模型名稱列表
models = [
   "gpt-35-turbo-16k",
   "gpt-4-turbo",
   "gpt-4o"
]
# 添加你的 headers 信息
headers = {
       "api-key": "H7UXkDQiYX6+frijH+aGDA==",
       "systemId": "0003R3"
}
# 準備發送到 OpenAI 的數據
payload = {
   "messages": [
       {"role": "system", "content": "你是金融專家"},
       {"role": "user", "content": "電動車的普及及如何影響保險行業的風險評估和定價策略?請簡要說明。"}
   ]
}
# 開啟 CSV 文件,準備寫入
with open('results.csv', 'w', newline='', encoding='utf-8') as csvfile:
   fieldnames = ['model', 'start_time', 'end_time', 'duration']
   writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
   writer.writeheader()
   for model in models:
       url = f"https://XXX-container.azurewebsites.net/gateway/chat/completions/{model}"
       for i in range(50):
           print(f"第 {i+1} 次 - 模型: {model}")
           start_time, end_time, duration = send_openai_request(url, headers, payload)
           writer.writerow({
               'model': model,
               'start_time': start_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
               'end_time': end_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
               'duration': duration
           })
           print('\n')
就可以產生.csv紀錄模型回應的時間囉!
那今天就先介紹到這啦,下一次要介紹的是
市面上Vector DB間的比較,選擇好Vector DB後
就可以準備開始進入RAG的實作囉!